import { routerMap } from '@/router';
import { RouteObject } from 'react-router-dom';

export const changeTreeDataField = (treeData: Array<any>, changeFieldList: Array<{ old: string; new: string }>, deleteFieldList?: Array<string>) => {
  const tempTreeData = [...treeData];
  
  tempTreeData.forEach(item => {
    changeFieldList.forEach(field => {
      if (item[field.old]) item[field.new] = item[field.old];
      Reflect.deleteProperty(item, field.old);

      if (item.children) item.children = changeTreeDataField(item.children, changeFieldList);
    });
    if (deleteFieldList) {
      deleteFieldList.forEach(field => {
        Reflect.deleteProperty(item, field);
        if (item.children) item.children = changeTreeDataField(item.children, changeFieldList);
      });
    }
  });
  return tempTreeData;
};

export const routerListToMenuList = (routerList: Array<RouteObject>) => {
  const menuList = routerList.filter(item => item.path === '/')[0].children?.map(item => (item.path ? item : { ...item, path: '/' }));

  // console.log('menuList', menuList);

  const formatterMenuList = (list: Array<RouteObject>) => {
    return list.map(item => {
      const mapItem = routerMap[item.path as string];
      if (!mapItem) return false;
      const tempItem: any = {
        key: item.path as string,
        label: mapItem.label,
        icon: mapItem.icon
      };
      if(item.children) {
        tempItem.children = formatterMenuList(item.children);
        if(tempItem.children.length === 0) Reflect.deleteProperty(tempItem, 'children')
      }
      return tempItem
    }).filter(item => Boolean(item))
  }

  return formatterMenuList(menuList ? menuList : [])
};

export const eachOwnProperty = (obj: any, callback: (item: any, key: string | symbol) => void) => {
  if (obj === null || typeof obj !== 'object') throw new TypeError('obj is not a object');
  if (typeof callback !== 'function') throw new TypeError('callback is not a function');
  // const keys = Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj) as any)
  const keys = Reflect.ownKeys(obj) //等同于上述写法，但ie浏览器不支持
  keys.forEach(key => {
    callback(obj[key], key)
  })
}

export const initRemUnit = () => {
  window.addEventListener('resize', () => {
    const html = document.documentElement;
    const width = html.clientWidth;
    const standerWidth = 750;
    const standerFontSize = 100;
    html.style.fontSize = (width / standerWidth) * standerFontSize + 'px';
  });
};